package org.batatasframework.support.searchable.result;

import java.sql.ResultSet;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.batatasframework.support.database.sql.field.SelectFragment;
import org.batatasframework.support.database.values.FieldValue;
import org.batatasframework.support.database.values.FieldValueHolder;


/**
 * TODO 这里需要支持多字段的分组和统计
 * @author jackson
 *
 * @param <Head>
 * @param <Row>
 */
public abstract class AbstractGroupResultStream<Head extends ResultHead, Row extends ResultRow> extends AbstractResultStream<Head, Row>{

	private static final long serialVersionUID = 5121317114650200993L;

	//统计时用来分组的字段
	protected final SelectFragment groupSelectFragment;
	
	public AbstractGroupResultStream(SelectFragment groupSelectFragment) throws Exception {
		this.groupSelectFragment = groupSelectFragment;
	}

	protected abstract Row buildGroupRow(List<Head> heads, FieldValue value);
	
	@Override
	protected void internalRead(ResultSet rs) throws Exception {
		Map<String, Row> rows = new TreeMap<>();
		Row groupRow;
		FieldValueHolder groupValueHolder = groupSelectFragment.getValueHolder();
		while(rs.next()){
			FieldValue groupValue = groupValueHolder.read(rs);
			String value = groupValue.targetValue().toString();
			groupRow = rows.get(value);
			if(null == groupRow){
				groupRow = buildGroupRow(heads, groupValue);
				rows.put(value, groupRow);
			}
			read(rs, groupRow);
		}
		this.rows.addAll(rows.values());
	}

	protected void read(ResultSet rs, Row groupRow) throws Exception {
		groupRow.read(rs);
	}
	
	
}
